﻿package akkz;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class login
 */

public class Login extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public Login()
	{
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
		
		request.setCharacterEncoding("UTF-8");
		
		try
		{
			int id = Integer.parseInt(request.getParameter("id"));
			String name = request.getParameter("name");

			StudentServer studentServer = (StudentServer) this.getServletContext().getAttribute("studentServer");
				
			Student student = studentServer.getStudent(id);			
				
			if ( student != null && name.equals(student.getName()) )
			{
				request.getSession().setAttribute("student", student);
				Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "login id: " + id + "\tname:" + name);

				if( student.getTel() == null )
				{
					request.setAttribute("security", "OK");
					request.getRequestDispatcher("/jsp/detailInput.jsp").forward(request, response);
				}
				else
				{
					request.getRequestDispatcher("/jsp/user.jsp").forward(request, response);
				}
			}
			else
			{
				Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "logingError id: " + id + "\tname:" + name);
				
				response.sendRedirect("/login.jsp?tip=equalError");
			}
		}
		catch (NumberFormatException e )
		{
			response.sendRedirect("/login.jsp?tip=idError");
		}
	}
}
